package cn._2dland.tools;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn._2dland.utils.HttpUtils;

public class VideoHelper extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String url = req.getParameter("url");
		String type = req.getParameter("type");
		try {
			if(url == null || type == null)
				throw new Exception("参数无效！");
			
			// 获取相应结果
			String result = null;
			if("56".equals(type)) {
				result = get56(url);
			}
			else if("6cn".equalsIgnoreCase(type)) {
				result = get6cn(url);
			}
			else if("tudou".equalsIgnoreCase(type)) {
				result = getTudou(url);
			}
			else {
				throw new Exception("不支持的解析类型！");
			}

			// 输出结果
			if(result != null) {
				resp.setContentLength(result.length());
				PrintWriter pw = resp.getWriter();
				pw.println(result);
				pw.flush();
				pw.close();
			}
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 获取56的视频信息码
	 * @param vid
	 * @return
	 */
	private String get56(String url) {
		String str = null;
		try {
			String body = HttpUtils.getHTTPContent(url);
			Matcher m = Pattern.compile("var _oFlv_o = '[^']+';").matcher(body);
			if(m.find()) {
				str = body.substring(m.start() + 15, m.end() - 2);
			}
		}
		catch (Exception e) {
			str = null;
			e.printStackTrace();
		}
		return str;
	}

	/**
	 * 获取6cn视频的EVID
	 * @param vid
	 * @return
	 */
	private String get6cn(String url) {
		String str = null;
		try {
			String body = HttpUtils.getHTTPContent(url);
			Matcher m = Pattern.compile("pageMessage\\.evid = '[^\\s]+'").matcher(body);
			if(m.find()) {
				str = body.substring(m.start() + 20, m.end()-1);
			}
		}
		catch (Exception e) {
			str = null;
			e.printStackTrace();
		}
		return str;
	}

	/**
	 * 获取土豆视频的IID
	 * @param vid
	 * @return
	 */
	private String getTudou(String url) {
		String str = null;
		try {
			String body = HttpUtils.getHTTPContent(url);
			Matcher m = Pattern.compile(",iid = \\d+\\s").matcher(body);
			if(m.find()) {
				str = body.substring(m.start() + 7, m.end()-1);
			}
		}
		catch (Exception e) {
			str = null;
			e.printStackTrace();
		}
		return str;
	}

}
